package top.songxs.yygh.service.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.songxs.yygh.common.exp.DiyException;
import top.songxs.yygh.common.utils.HttpRequestHelper;
import top.songxs.yygh.enums.OrderStatusEnum;
import top.songxs.yygh.enums.PaymentStatusEnum;
import top.songxs.yygh.hosp.client.HospitalFeignClient;
import top.songxs.yygh.model.order.OrderInfo;
import top.songxs.yygh.model.order.PaymentInfo;
import top.songxs.yygh.service.order.mapper.PaymentMapper;
import top.songxs.yygh.service.order.service.OrderInfoService;
import top.songxs.yygh.service.order.service.PaymentService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//支付记录
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {


    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    HospitalFeignClient hospitalFeignClient;
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer status) {
        //1、根据订单id和支付方式查询支付记录，如果存在直接return
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderInfo.getId());
        queryWrapper.eq("payment_type",status);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count>0) return; //如果已经存在则直接返回 方法不执行
        //2、保存交易记录
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setPaymentType(status);
        paymentInfo.setOrderId(orderInfo.getId());
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());

        //  //2023-01-07|北京协和医院|科室名称|副主任医师
        String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")+"|"+orderInfo
                .getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
        paymentInfo.setSubject(subject);
        paymentInfo.setTotalAmount(orderInfo.getAmount());
        this.baseMapper.insert(paymentInfo);
    }

    @Override
    public void paySuccess(Map<String, String> map) {
        //0、根据out_trade_no查询订单
        String out_trade_no = map.get("out_trade_no");
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no",out_trade_no);
        OrderInfo orderInfo = orderInfoService.getOne(queryWrapper);

        //1、调用医院端的“更新支付状态接口”，将医院端订单的状态改成1--已支付
        String hoscode =orderInfo.getHoscode();
        //获取医院设置中的apiUrl属性
        String apiUrl = hospitalFeignClient.getApiUrl(hoscode);
        String url = "http://"+apiUrl + "/order/updatePayStatus";

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",hoscode);
        paramMap.put("hosRecordId",orderInfo.getHosRecordId());//医院端订单的id

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, url);
//        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, url);
        Integer code = jsonObject.getInteger("code");
        if(code!=200){
            //医院端更新订单支付状态接口调用失败
            throw new DiyException(20001,"医院端更新订单支付状态接口调用失败");
        }
        //2、并更新平台端订单状态为已支付
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderInfoService.updateById(orderInfo);


        //3、根据out_trade_no查询支付记录，更新支付记录状态为已支付
        QueryWrapper<PaymentInfo> wrapperPayment = new QueryWrapper<>();
        wrapperPayment.eq("out_trade_no",out_trade_no);
        PaymentInfo paymentInfo = baseMapper.selectOne(wrapperPayment);
        //设置状态和tradeNo+callback字段
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setTradeNo(map.get("transaction_id"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(map.toString());

        baseMapper.updateById(paymentInfo);
    }

    @Override
    public PaymentInfo getByOrderId(Long orderId) {

        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        return this.baseMapper.selectOne(wrapper);
    }
}
